package com.shxc.smarttrade.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.account.activity.ForceActivity;
import com.shxc.smarttrade.account.fragment.AccountFragment;
import com.shxc.smarttrade.base.BaseActivity;
import com.shxc.smarttrade.community.fragment.CommunityAndroidFragment;
import com.shxc.smarttrade.dialog.DownloadDialog;
import com.shxc.smarttrade.dialog.UpdateDialog;
import com.shxc.smarttrade.dialogactivity.AccExpireDialogActivity;
import com.shxc.smarttrade.dialogactivity.FirstLoginDialogActivity;
import com.shxc.smarttrade.dialogactivity.TigerAccDialogActivity;
import com.shxc.smarttrade.dialogactivity.TigerErrorDialogActivity;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.login.activity.LoginIndexActivity;
import com.shxc.smarttrade.old.bean.AccountStatus;
import com.shxc.smarttrade.old.bean.ChartRoomInfo;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.SwitchBean;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.foreignfragment.SimpleTransFragment;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.other.model.PullVersionModel;
import com.shxc.smarttrade.position.old.PositionFragment;
import com.shxc.smarttrade.quotation.fragment.QuotationFragment;
import com.shxc.smarttrade.utils.AnimationUtils;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.img_home)
    ImageView imgHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.img_trans)
    ImageView imgTrans;
    @BindView(R.id.tv_trans)
    TextView tvTrans;
    @BindView(R.id.img_position)
    ImageView imgPosition;
    @BindView(R.id.tv_position)
    TextView tvPosition;
    @BindView(R.id.img_account)
    ImageView imgAccount;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.ll_trans)
    LinearLayout llTrans;
    @BindView(R.id.ll_position)
    LinearLayout llPosition;
    @BindView(R.id.ll_account)
    LinearLayout llAccount;
    @BindView(R.id.ll_analyze)
    LinearLayout llAnalyze;
    @BindView(R.id.img_analyze)
    ImageView imgAnalyze;
    @BindView(R.id.tv_analyze)
    TextView tvAnalyze;
    @BindView(R.id.ll_draw_all)
    LinearLayout llDrawAll;
    @BindView(R.id.bottom_view)
    LinearLayout bottom_view;

    Fragment[] mFragment;

    //    IndexFragment mHomeFragments;
    QuotationFragment mTransactionFragment;//行情
    PositionFragment mPositionFragment;//持仓
    CommunityAndroidFragment mCommunityFragment;//社区 新
    AccountFragment mAccountFragments;//新 1

    SimpleTransFragment mSimpleTransFragment;

    private int mIndex;
    private boolean isChange = false;
    public long userId = -1;
    private String accessToken = "";
    private int status = -1;
    private MyProgressDialog shortDialog;

    private UpdateDialog updateDialog;
    private boolean isForce = false;
    private String apkUrl;
    private String apkName;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    RealTimeQuoteDatas rd = (RealTimeQuoteDatas) msg.obj;
                    if (rd.getErr_code().equals("0")) {
                        List<RealTimeQuoteDatas.DataBean.QuoteBean> ab = rd.getData().getQuote();
                        int where = msg.arg1;
                        //给首页和交易界面发送实时数据
                        if (where == 5) {
//                            EventBus.getDefault().post(new EventDatas(EventContents.MAIN_ACTIVITY_REAL_TIME_QUOTE_ONE, ab));
                        } else if (where == 0) {
                            EventBus.getDefault().post(new EventDatas(EventContents.MAIN_ACTIVITY_REAL_TIME_QUOTE_TWO, ab));
                        } else if (where == 1) {
                            EventBus.getDefault().post(new EventDatas(EventContents.MAIN_ACTIVITY_REAL_TIME_QUOTE_FIVE, ab));
                        }
                    } else {
                        ToastUtils.showToast(rd.getErr_msg());
                    }
                    break;
                case 1:
                    boolean haveMsg = (boolean) msg.obj;
                    EventBus.getDefault().post(new EventDatas(EventContents.MAIN_ACTIVITY_HAVE_MESSAGE, haveMsg));
                    break;
                case 2:
                    AccountStatus.DataBean asdb = (AccountStatus.DataBean) msg.obj;
                    if (MyApplication.tagTwo == 2) return;
                    MyApplication.tagTwo = 2;
                    if (userId == -1) return;
                    if (asdb.getAccType() == -1 || asdb.getAccType() == 1) return;
                    //优先提示开户未通过信息
                    if (!asdb.isIsOpen()) {
                        int errMsg = asdb.getOpenError().getMsgCount();
                        int spErrorMsg = SpUtils.getInt(MainActivity.this, "errMsg", 0);
                        if (errMsg != 0 && spErrorMsg != errMsg) {
                            showRemind(4, asdb.getOpenError().getMsgInfo());
                            SpUtils.putInt(MainActivity.this, "errMsg", errMsg);
                            return;
                        }
                    }

                    if (asdb.isIsOpen() && !asdb.isDestory()) {//tag=0:开户未过期
                        showRemind(0, "");
                    } else if (asdb.isIsOpen() && asdb.isDestory()) {//tag==1:开户已过期
                        showRemind(1, "");
                    } else if (!asdb.isIsOpen() && !asdb.isDestory()) {//tag==2：未开户未过期
                        return;
//                        showRemind(2);
                    } else if (!asdb.isIsOpen() && asdb.isDestory()) {//tag==3：未开户已过期
                        showRemind(3, "");
                    }
                    break;
                case 3:
                    ChartRoomInfo.DataBeanX.DataBean cdb = (ChartRoomInfo.DataBeanX.DataBean) msg.obj;
                    SpUtils.putString(MainActivity.this, "chartRoomId", cdb.getChatroomId());
                    SpUtils.putString(MainActivity.this, "customerServiceId", cdb.getCustomerServiceId());
                    Loger.e("token", cdb.getToken());
                    connect(cdb.getToken(), cdb.getUserId(), cdb.getUserName(), cdb.getUserPortrait());
                    break;
                case 4:
                    SwitchBean.DataBean sdb = (SwitchBean.DataBean) msg.obj;
                    SpUtils.putBoolean(MainActivity.this, "dealSwitch", sdb.getConfig().isDealSwitch());//baidu
//                    SpUtils.putBoolean(MainActivity2.this, "dealSwitch", true);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
//        RongIM.getInstance().setCurrentUserInfo(new UserInfo("666", "forex666", Uri.parse("http://img3.imgtn.bdimg.com/it/u=634098145,264198475&fm=214&gp=0.jpg")));
//        RongIM.getInstance().setMessageAttachedUserInfo(true);

        pullVersion();


        CloseAllActivity.getScreenManager().pushActivity(this);

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initFragment();
        initListener();
        MyApplication.tag = 1;
//        聊天室
//        getConversationToken();
        checkHaveMsg();
        checkAccountStatus();
        getONOrOFF();

        MyApplication.getInstance().setMainActivity(this);

        jump(getIntent().getIntExtra("status", 0));
    }

    public void jump(int status) {
        switch (status) {
            case 3:
                setIndexSelected(2);
                selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 1);
                selectTextColor(tvAnalyze, tvTrans, tvHome, tvPosition, tvAccount);
                break;
            case 5:
                setIndexSelected(4);
                selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 3);
                selectTextColor(tvAccount, tvHome, tvTrans, tvPosition, tvAnalyze);
                break;
        }
    }

    private void initView() {
        userId = spImp.getUserId();
        accessToken = SpUtils.getString(getApplicationContext(), "accessToken", "");
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        mTransactionFragment = new QuotationFragment();
        mPositionFragment = new PositionFragment();
//        mHomeFragments = new IndexFragment();
        mCommunityFragment = new CommunityAndroidFragment();
        mAccountFragments = new AccountFragment();

        mSimpleTransFragment = new SimpleTransFragment();
//        mFragment = new Fragment[]{mHomeFragments, mTransactionFragment, mPositionFragment, mCommunityFragment, mAccountFragments};
        mFragment = new Fragment[]{mTransactionFragment, mPositionFragment, mCommunityFragment, mAccountFragments};
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();   //开启事务

        //默认设置为第1个
        String from = getIntent().getStringExtra("from");
        if (from != null && from.equals("loginActivity")) {
            ft.add(R.id.content, mAccountFragments).commit();   //账户
            mIndex = 3;
            setIndexSelected(3);
            selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 4);
            selectTextColor(tvAccount, tvHome, tvTrans, tvPosition, tvAnalyze);
        } else {
            goThree();
            ft.hide(mFragment[2]);
            ft.add(R.id.content, mTransactionFragment).commit();   //首页
            mIndex = 0;
            setIndexSelected(0);
        }

    }

    private void goThree() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();   //开启事务
        ft.add(R.id.content, mCommunityFragment).commit();   //打开第三个页面
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
//        llHome.setOnClickListener(this);
        llTrans.setOnClickListener(this);
        llAnalyze.setOnClickListener(this);
        llPosition.setOnClickListener(this);
        llAccount.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.ll_home:
//                setIndexSelected(0);
//                selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 0);
//                selectTextColor(tvHome, tvTrans, tvPosition, tvAccount, tvAnalyze);
//                break;
            case R.id.ll_trans:
                setIndexSelected(0);
                selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 0);
                selectTextColor(tvTrans, tvHome, tvPosition, tvAccount, tvAnalyze);
                break;
            case R.id.ll_analyze:
                setIndexSelected(1);
                selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 1);
                selectTextColor(tvAnalyze, tvTrans, tvHome, tvPosition, tvAccount);
                break;
            case R.id.ll_position:
                setIndexSelected(2);
                selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 2);
                selectTextColor(tvPosition, tvHome, tvTrans, tvAccount, tvAnalyze);
                break;
            case R.id.ll_account:
                if (spImp.getUserId() == -1) {
                    jumpType = 1;
                    JumpTo(LoginIndexActivity.class);
                } else {
                    setIndexSelected(3);
                    selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 3);
                    selectTextColor(tvAccount, tvHome, tvTrans, tvPosition, tvAnalyze);
                }
                break;
        }

    }

    /**
     * 控制Fragment的显示与隐藏
     *
     * @param index
     */
    private void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }

        //发送消息告知当前界面是哪个
        if (index == 0) {
            stopTimerListener();
//            mHomeFragment.startListener();
        } else if (index == 1) {
            stopTimerListener();
//            mTransactionFragment.startListener();

        } else if (index == 2) {
            stopTimerListener();

        } else {
            stopTimerListener();
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        //隐藏
        ft.hide(mFragment[mIndex]);
        //判断是否添加
        if (!mFragment[index].isAdded()) {
            ft.add(R.id.content, mFragment[index]).show(mFragment[index]);
        } else {
            ft.show(mFragment[index]);
        }
        ft.commit();
        //再次赋值
        mIndex = index;
    }

    /**
     * 导航栏按钮选择器
     */
    private void selectImageResouse(ImageView a, ImageView b, ImageView c, ImageView d, ImageView f, int e) {
//        if (e == 0) {
//            fragment = mHomeFragments;
//            a.setImageResource(R.mipmap.home_click);
//            b.setImageResource(R.mipmap.transaction_normal);
//            c.setImageResource(R.mipmap.community_normal);
//            d.setImageResource(R.mipmap.account_normal);
//            f.setImageResource(R.mipmap.position_normal);
//        } else if (e == 1) {
//            fragment = mTransactionFragment;
//            a.setImageResource(R.mipmap.home_normal);
//            b.setImageResource(R.mipmap.transaction_click);
//            c.setImageResource(R.mipmap.community_normal);
//            d.setImageResource(R.mipmap.account_normal);
//            f.setImageResource(R.mipmap.position_normal);
//        } else if (e == 3) {
//            fragment = mCommunityFragment;
//            a.setImageResource(R.mipmap.home_normal);
//            b.setImageResource(R.mipmap.transaction_normal);
//            c.setImageResource(R.mipmap.community_click);
//            d.setImageResource(R.mipmap.account_normal);
//            f.setImageResource(R.mipmap.position_normal);
//        } else if (e == 4) {
//            fragment = mAccountFragments;
//            a.setImageResource(R.mipmap.home_normal);
//            b.setImageResource(R.mipmap.transaction_normal);
//            c.setImageResource(R.mipmap.community_normal);
//            d.setImageResource(R.mipmap.account_click);
//            f.setImageResource(R.mipmap.position_normal);
//        } else if (e == 2) {
//            fragment = mPositionFragment;
//            a.setImageResource(R.mipmap.home_normal);
//            b.setImageResource(R.mipmap.transaction_normal);
//            c.setImageResource(R.mipmap.community_normal);
//            d.setImageResource(R.mipmap.account_normal);
//            f.setImageResource(R.mipmap.position_click);
//        }
        if (e == 0) {
            fragment = mTransactionFragment;
            a.setImageResource(R.mipmap.home_normal);
            b.setImageResource(R.mipmap.transaction_click);
            c.setImageResource(R.mipmap.community_normal);
            d.setImageResource(R.mipmap.account_normal);
            f.setImageResource(R.mipmap.position_normal);
        } else if (e == 1) {
            fragment = mPositionFragment;
            a.setImageResource(R.mipmap.home_normal);
            b.setImageResource(R.mipmap.transaction_normal);
            c.setImageResource(R.mipmap.community_normal);
            d.setImageResource(R.mipmap.account_normal);
            f.setImageResource(R.mipmap.position_click);
        } else if (e == 2) {
            fragment = mCommunityFragment;
            a.setImageResource(R.mipmap.home_normal);
            b.setImageResource(R.mipmap.transaction_normal);
            c.setImageResource(R.mipmap.community_click);
            d.setImageResource(R.mipmap.account_normal);
            f.setImageResource(R.mipmap.position_normal);
        } else if (e == 3) {
            fragment = mAccountFragments;
            a.setImageResource(R.mipmap.home_normal);
            b.setImageResource(R.mipmap.transaction_normal);
            c.setImageResource(R.mipmap.community_normal);
            d.setImageResource(R.mipmap.account_click);
            f.setImageResource(R.mipmap.position_normal);
        }
    }

    /**
     * 导航栏文字颜色选择器
     */
    private void selectTextColor(TextView a, TextView b, TextView c, TextView d, TextView e) {
        a.setTextColor(getResources().getColor(R.color.main_color));
        b.setTextColor(getResources().getColor(R.color.tab_text));
        c.setTextColor(getResources().getColor(R.color.tab_text));
        d.setTextColor(getResources().getColor(R.color.tab_text));
        e.setTextColor(getResources().getColor(R.color.tab_text));

    }

    private Runnable runnable;

    /**
     * 开启实时数据推送
     *
     * @param symbol
     * @param where
     */
    public void startTimerListener(String symbol, int where) {
        stopTimerListener();
        initTimerListener(symbol, where);
        handler.post(runnable);
    }

    /**
     * 关闭实时数据推送
     */
    public void stopTimerListener() {
        if (runnable != null && handler != null)
            handler.removeCallbacks(runnable);
    }

    private void initTimerListener(final String symbol, final int where) {
        runnable = new Runnable() {
            @Override
            public void run() {
                getRealTimeQuote(symbol, where);
                handler.postDelayed(this, 1500);
            }
        };
    }

    /**
     * 获取实时数据
     *
     * @param symbol
     */
    private void getRealTimeQuote(String symbol, final int where) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("symbol", symbol);
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.HOME_FRAGMENT_REALTIMEQUOTE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {

            }

            @Override
            public void success(String response, int id) {
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    try {
                        ToastUtils.showToast(getString(R.string.data_error));
                    } catch (Exception e) {
                    }
                    return;
                }
                Gson gson = new Gson();
                RealTimeQuoteDatas rd = gson.fromJson(response, RealTimeQuoteDatas.class);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = rd;
                msg.arg1 = where;
                handler.sendMessage(msg);
            }
        });

    }


    /**
     * 解决了Fragment重叠的问题
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (mHomeFragments.scrollview != null)
//            mHomeFragments.scrollview.smoothScrollTo(0, 0);

        MobclickAgent.onResume(this);
        if (isChange) {
            setIndexSelected(1);
            selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 1);
            selectTextColor(tvPosition, tvHome, tvTrans, tvAccount, tvAnalyze);
            isChange = false;
        }

        if (status != -1) {
            jump(status);
            status = -1;
        }

        if (mIndex == 0) {
//            mHomeFragment.startListener();

        } else if (mIndex == 0) {
//            mTransactionFragment.startListener();

        } else if (mIndex == 1) {
            mPositionFragment.startListener();
        } else {
            stopTimerListener();
        }

        //判断是否首次登录
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                judgeIsFirstLogin();
            }
        }, 100);

        if(userId==-1 && spImp.getUserId()!=-1){
            setIndexSelected(3);
            selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 3);
            selectTextColor(tvAccount, tvHome, tvTrans, tvPosition, tvAnalyze);

//            getConversationToken();

            userId = spImp.getUserId();
        }else if(userId!=-1 && spImp.getUserId()==-1){
            setIndexSelected(0);
            selectImageResouse(imgHome, imgTrans, imgPosition, imgAccount, imgAnalyze, 0);
            selectTextColor(tvAccount, tvHome, tvTrans, tvPosition, tvAnalyze);
            userId = spImp.getUserId();
        }


}

    /**
     * 判断是否是首次登录
     */
    private void judgeIsFirstLogin() {
//        if (SpUtils.getBoolean(this, "firstLogin")) {
//            //弹出提示框
//            View view = View.inflate(this, R.layout.pop_first_login_remind, null);
//            TextView tvSure = (TextView) view.findViewById(R.id.tv_sure);
//            final PopupWindow popupWindow = BaseView.showPopupWindow(view, this, R.layout.activity_main, Gravity.CENTER, 0.5f);
//            tvSure.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    popupWindow.dismiss();
//                }
//            });
//            SpUtils.putBoolean(this, "firstLogin", false);
//        }
        if (spImp.isFirstLogin()) {
            jumpType = 1;
            JumpTo(FirstLoginDialogActivity.class);
            spImp.setFirstLogin(false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        stopTimerListener();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stopTimerListener();
        CloseAllActivity.getScreenManager().popActivity(this);
        new Thread() {
            @Override
            public void run() {
                super.run();
                Glide.get(MainActivity.this).clearDiskCache();
            }
        }.start();
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE)) {
            isChange = true;
        } else if (event.getTagOne().equals(EventContents.PENDING_CONTROL_FINISH_PENDING)) {
            isChange = true;
        } else if (event.getTagOne().equals(EventContents.MESSAGE_ACTIVITY_READ_MSG)) {
            checkHaveMsg();
        } else if (event.getTagOne().equals(EventContents.PERSON_INFO_CHANGE_INFO)) {
            //重新获取聊天信息
//            getConversationToken();
        } else if (event.getTagOne().equals(EventContents.DIALOG_PUSH_SEND_MSG)) {
            status = (int) event.getResponse();
        }
    }

//    /**
//     * 方便发射Toast
//     */
//    public void ToastUtils.showToast(String str) {
//        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
//    }


    /**
     * 账户状态提示信息
     */
    private void showRemind(final int tag, String errMsgInfo) {//tag=0:开户未过期  tag==1:开户已过期  tag==2：未开户未过期 tag==3：未开户已过期
        switch (tag) {
            case 0:
                //老虎 真实账户开立成功
                if (spImp.getAccStatus() ==0) {
                    jumpType = 1;
                    JumpTo(TigerAccDialogActivity.class);
                }
                break;
            case 1:
                //模拟账户已过期
                jumpType = 1;
                JumpTo(AccExpireDialogActivity.class);
                break;
            case 3:
                //未开户已过期
                jumpType = 1;
                JumpTo(AccExpireDialogActivity.class);
                break;
            case 4:
                //审核未通过
                jumpType = 2;
                bundle.putString("error",errMsgInfo);
                JumpTo(TigerErrorDialogActivity.class,bundle);
                break;
        }
    }

//    private void showRemind(final int tag, String errMsgInfo) {//tag=0:开户未过期  tag==1:开户已过期  tag==2：未开户未过期 tag==3：未开户已过期
//
//        //弹出提示框
//        View view = View.inflate(this, R.layout.pop_account_remind, null);
//        TextView tvTitle = (TextView) view.findViewById(R.id.tv_titles);
//        TextView tvContent = (TextView) view.findViewById(R.id.tv_contents);
//        TextView tvSure = (TextView) view.findViewById(R.id.tv_sure);
//        TextView tvSwitch = (TextView) view.findViewById(R.id.tv_switch_over);
//        TextView tvWait = (TextView) view.findViewById(R.id.tv_wait);
//        LinearLayout llAllBottom = (LinearLayout) view.findViewById(R.id.ll_all_bottom);
//        if (tag == 0) {
//            tvTitle.setText("真实账户开立成功！");
//            tvContent.setText("您的开户申请已被经纪商审核通过，现在即可切换至真实账户。");
//            llAllBottom.setVisibility(View.VISIBLE);
//        } else if (tag == 1) {
//            tvTitle.setText("模拟账户已过期！");
//            tvContent.setText("您的模拟账户已到期，请切换至真实账户。");
//            tvSure.setVisibility(View.VISIBLE);
//            tvSure.setText("立即切换");
//        } else if (tag == 3) {
//            tvTitle.setText("模拟账户已过期！");
//            tvContent.setText("您的模拟账户已到期，请到个人中心开设真实账户。");
//            tvSure.setVisibility(View.VISIBLE);
//        } else if (tag == 4) {
//            tvTitle.setText("审核未通过！");
//            tvContent.setText(errMsgInfo);
//            llAllBottom.setVisibility(View.VISIBLE);
//            tvSwitch.setText("查看详情");
//
//        }
//
//        final PopupWindow popupWindow = BaseView.showPopupWindow(view, this, R.layout.activity_main, Gravity.CENTER, 0.5f);
//        tvSure.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (tag == 1) {
//                    jumpType = 2;
//                    JumpTo(TradeAccountActivity.class);
//                }
//                popupWindow.dismiss();
//            }
//        });
//        tvSwitch.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (tag == 4) {
//                    jumpType = 2;
//                    JumpTo(SelectBrokeOpenAccountActivity.class);
//                } else {
//                    jumpType = 2;
//                    JumpTo(TradingAccountActivity.class);
//                }
//                popupWindow.dismiss();
//            }
//        });
//        tvWait.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popupWindow.dismiss();
//            }
//        });
//
//    }

    /**
     * 获取聊天基本信息
     */
    private void getConversationToken() {
        if (userId == -1) return;
        Loger.e("getConversationToken", "ssssssss");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", String.valueOf(userId));
        map.put("accessToken", accessToken);
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.MAINACTIVITY_CHARTROOM_GETTOKEN, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                ToastUtils.showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Loger.e("聊天室token",response);
                    Gson gsom = new Gson();
                    ChartRoomInfo ci = gsom.fromJson(response, ChartRoomInfo.class);
                    if (ci.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 3;
                        msg.obj = ci.getData().getData();
                        handler.sendMessage(msg);
                        Loger.e("getConversationToken", "success");
                    } else
                        ToastUtils.showToast(ci.getErr_msg());
                }

            }
        });


    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 init 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token, final String id, final String name, final String headUrl) {
        RongIM.getInstance().disconnect();
//        if (TextUtils.isEmpty(rongimtoken)) return;
        if (getApplicationInfo().packageName.equals(MyApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    Loger.e("onTokenIncorrect", "...");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    Loger.e("userId-success", userid);
                    RongIM.getInstance().setCurrentUserInfo(new UserInfo(id, name, Uri.parse(headUrl)));
                    RongIM.getInstance().setMessageAttachedUserInfo(true);
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Loger.e("errCode:", errorCode.getMessage());
                }
            });
        }
    }


    /**
     * 检查是否还有新消息
     */
    private void checkHaveMsg() {
        if (userId == -1) return;
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessToken);
        map.put("userId", String.valueOf(userId));
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.MAINACTIVITY_HAVEMSG, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                ToastUtils.showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    boolean haveMsg = false;
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        JsonObject data = jsonObject.get("data").getAsJsonObject();
                        if (!data.get("haveMsg").isJsonNull()) {
                            haveMsg = data.get("haveMsg").getAsBoolean();
                            Message msg = Message.obtain();
                            msg.what = 1;
                            msg.obj = haveMsg;
                            handler.sendMessage(msg);
                        }

                    } else
                        ToastUtils.showToast(errMsg);
                }
            }
        });
    }

    /**
     * 检查账户状态
     */
    private void checkAccountStatus() {
        if (userId == -1) return;
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessToken);
        map.put("userId", String.valueOf(userId));
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.MAINACTIVITY_ACCOUNT_CHECKACCOUNTINFO, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                ToastUtils.showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    AccountStatus as = gson.fromJson(response, AccountStatus.class);
                    if (as.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 2;
                        msg.obj = as.getData();
                        handler.sendMessage(msg);
                    } else {
                        BaseUtils.showToast(as.getErr_msg(), MainActivity.this);
                    }
                }
            }
        });
    }

    public void showDialog() {
        if (shortDialog == null) {
            shortDialog = new MyProgressDialog(this);
            shortDialog.setCancelable(false);
        }
        shortDialog.show();
    }

    public void dissDialog() {
        if (shortDialog != null)
            shortDialog.dismiss();
    }

    //{"0:应用宝", "1:华为", "2:360", "3:小米", "4:oppo", "5:联想", "6:阿里", "7:魅族", "8:百度"}
    private void getONOrOFF() {
        Map<String, Object> map = new HashMap<>();
        map.put("version", getResources().getString(R.string.version_name));
        map.put("os", "Android");
        map.put("channel", getResources().getString(R.string.channel));
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.MAIN_OFF_OR_ON, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                ToastUtils.showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {

                if (response != null) {

                    Loger.e("ressssssssssssss", response);
                    Gson gson = new Gson();
                    SwitchBean switchBean = gson.fromJson(response, SwitchBean.class);
                    if (switchBean.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 4;
                        msg.obj = switchBean.getData();
                        handler.sendMessage(msg);
                    }
                }
            }
        });

    }

    public void changeBottomVisibility(int isVisibility) {
        bottom_view.setVisibility(isVisibility);
        switch (isVisibility) {
            case View.VISIBLE:
                bottom_view.setAnimation(AnimationUtils.moveToViewLocation());
                break;
            case View.GONE:
                bottom_view.setAnimation(AnimationUtils.moveToViewBottom());
                break;
        }
    }

    Fragment fragment;

    //连续两次点击后退出应用
    private long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    //更新firstTime
                    return true;
                } else {
                    //两次按键小于2秒时，退出应用
                    finish();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }


    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    private DownloadDialog downloadDialog;

    /**
     * 获取版本号
     *
     * @return
     * @throws Exception
     */
    public String getVersionName() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (Exception e) {
            return getResources().getString(R.string.version_name);//TODO 修改版本号
        }
    }

    /**
     * 下载apk
     */
    private void okhttpDownload() {
        downloadDialog.show();
        OkHttpUtils.get()
                .url(spImp.getUpdateurl())
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(),
                        apkName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Loger.e("download", "onError :" + e.getMessage());
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        //super.inProgress(progress, total, id);
                        if (progress != 100) {
                            downloadDialog.getProgressbar().setProgress((int) (100 * progress));
                            downloadDialog.getPersent_textview().setText((int) (100 * progress) + "%");
                        } else {
                            downloadDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(File file, int id) {
                        Loger.e("download", "onResponse :" + file.getAbsolutePath());
                        installApk();
                    }
                });
    }

    //安装apk
    public void installApk() {
        String providerName = getApplicationInfo().packageName + ".provider";
        Loger.e("providerName", providerName);

        File file = new File(apkUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, providerName, file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(apkUri, "applicationnd.android.package-archive");
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.parse("file://" + apkUrl),
//                    "applicationnd.android.package-archive");
                    "application/vnd.android.package-archive");

        }
        jumpType = 0;
        startActivity(intent);
    }

    // 授权管理 - 写入权限
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请在 setting-应用管理 中开启此应用的储存授权。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            okhttpDownload();
        }
    }

    // 授权返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Loger.e("initPermissions", "同意授权");
                    okhttpDownload();
                } else {
                    Loger.e("initPermissions", "拒绝授权");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public static int jumpType = 0;


    protected void overridePendingTransitionEnter() {
        switch (jumpType) {
            case 1:
                //上下
                overridePendingTransition(R.anim.slide_from_bottom, R.anim.slide_notmove);
                break;
            case 2:
            default:
                //左右
                overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
                break;
        }
    }

    private void pullVersion() {

        com.shxc.smarttrade.utils.MyOkHttpUtils.getServiceDatas(null, Contents.UPDATEVERSION_PULLVERSION, new com.shxc.smarttrade.utils.MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {

                Loger.e("update - ", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, PullVersionModel.class);
                    if (jam.isSuccess()) {
                        PullVersionModel model = (PullVersionModel) jam.getData();
                        spImp.setNewversion(model.getData().getVaersion());
                        spImp.setForce(model.getData().getIsForce() == 0 ? false : true);
                        spImp.setUpdatemsg(model.getData().getUpdateMsg());
                        spImp.setUpdateurl(model.getData().getUpdateUrl());


                        checkUpdate();
                    } else {
                        Loger.e("error_msg", jam.getMsg());
//                        ToastUtils.ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    private void checkUpdate() {

        //下载更新部分
        String[] ss = spImp.getUpdateurl().split("/");
        apkName = ss[ss.length - 1];
        apkUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + ss[ss.length - 1];

        Loger.e("new - ", spImp.getNewversion());
        Loger.e("old - ", getVersionName());

        int newCode = Integer.parseInt(spImp.getNewversion().replace(".", ""));
        int oldCode = Integer.parseInt(getVersionName().replace(".", ""));

        //版本是否为当前版本
        if (newCode > oldCode) {
            if (spImp.isForce()) {
                //强制
                jumpType = 1;
                JumpTo(ForceActivity.class);
            } else {
                //不强制，一天一次
                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH) + 1;
                int day = c.get(Calendar.DAY_OF_MONTH);
                String today = year + "-" + month + "-" + day;

                if (!today.equals(spImp.getToday())) {
                    spImp.setToday(today);
                    updateDialog = new UpdateDialog(this, getResources().getIdentifier("MyDialog", "style", getPackageName()));
                    updateDialog.showDialog(spImp.getUpdatemsg());
                    updateDialog.getCancel_textview().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.dismiss();
                        }
                    });
                    updateDialog.getSubmit_textview().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.dismiss();
                            if (fileIsExists(apkUrl)) {
                                installApk();
                            } else {
                                initPermissions();
                            }
                        }
                    });
                }
            }
        }

    }


}
